/*
 * Copyright (C) 2011 Young,Fey <fey.young@gmail.com>
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * 
 */

package com.youngfey.sqlite
import java.sql.Types

/**
 * SQLite支持的数据类型
 * @author Young,Fey <fey.young@gmail.com>
 */
enum DataType {
    INTEGER, REAL, TEXT, BLOB,
    /**
     * 当SQLite本身未指定使用何种类型时，则使用DYNAMIC表示
     */
    DYNAMIC,
    /**
     * 本身为SQLite类型，但不应用于DDL，也不会出现在读取表结构的过程中
     */
    NULL

    /**
     * 将给定的类型转换为SQLite数据类型
     */
    private static DataType conv(Class c) {
        switch(c) {
            case [Short.class, Integer.class, BigInteger.class, Long.class]:
            INTEGER
            break
            case [Double.class, Float.class, BigDecimal.class]:
            REAL
            break
            default: TEXT
        }
    }

    /**
     * @return 返回指定对象的SQLite数据类型
     */
    private static DataType getType(obj) {
        obj == null ? NULL : conv(obj.getClass())
    }

    /**
     * 猜测字符串对应的DataType
     * 由于SQLite为动态类型，因此实际应用中会遇到与
     * java.sql.Types完全不同的类型，因此对不明类型如无法进
     * 行合理猜测则定义为DYNAMIC
     */
    private static DataType getInstance(String key) {
        if(!key) {
            return DYNAMIC
        }

        key = key.toUpperCase()
        if(values().collect { it.toString() }.contains(key)) { 
            return valueOf(key)
        }

        if(key.endsWith('INT') ||
                ['INT64', 'SHORT', 'LONG', 'BOOL', 'BOOLEAN', 'AUTOINC'].contains(key)) {
            return INTEGER
        } else if(key.contains('CHAR') || key.endsWith('TEXT') || ['CLOB'].contains(key)) {
            return TEXT
        } else if(['FLOAT', 'DOUBLE', 'NUMBER',
                'DECIMAL', 'NUM', 'NUMERIC'].contains(key)) {
            return REAL
        } else if(key.endsWith('BLOB') || key.contains('BINARY') || key == 'IMAGE') {
            return BLOB
        }

        DYNAMIC
    }
}

